package com.ssy.lingxi.marketing.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.json.JSONUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.MemberAndRoleIdDTO;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.rabbitMQ.service.IRabbitMQUtils;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.marketing.api.model.constant.MkFeignConstants;
import com.ssy.lingxi.marketing.api.model.constant.MkQueueMessageTypeEnum;
import com.ssy.lingxi.marketing.api.model.constant.MkRedisKeyConstants;
import com.ssy.lingxi.marketing.api.model.dto.MarketingQueueDTO;
import com.ssy.lingxi.marketing.api.model.request.*;
import com.ssy.lingxi.marketing.api.model.response.*;
import com.ssy.lingxi.marketing.entity.activity.*;
import com.ssy.lingxi.marketing.model.bo.GroupPurchaseBO;
import com.ssy.lingxi.marketing.model.constant.GroupPurchaseStatusEnum;
import com.ssy.lingxi.marketing.model.dto.*;
import com.ssy.lingxi.marketing.repository.*;
import com.ssy.lingxi.marketing.service.IActivityOrderService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityService;
import com.ssy.lingxi.order.api.model.constant.OrderFeignConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 活动订单服务实现类
 *
 * @author ds
 * @version 2.0.0
 * @date 2021/11/23
 */
@Slf4j
@Service
public class ActivityOrderServiceImpl implements IActivityOrderService {
    @Resource
    private JPAQueryFactory queryFactory;
    @Resource
    private ActivityOrderRecordRepository activityOrderRecordRepository;
    @Resource
    private GroupPurchaseRecordRepository groupPurchaseRecordRepository;
    @Resource
    private PlatformActivityRepository platformActivityRepository;
    @Resource
    private MerchantActivityRepository merchantActivityRepository;
    @Resource
    private IRedisStringUtils redisStringUtils;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IRabbitMQUtils rabbitMQUtils;
    @Resource
    private ActivityShopRepository shopRepository;
    @Resource
    private ActivityGoodsRepository goodsRepository;
    @Resource
    private BaseActivityService baseActivityService;
    /**
     * 手机号脱敏
     *
     * @param mobileNum
     * @return 133****1234
     */
    private String mobileHide(String mobileNum) {
        if (mobileNum != null && mobileNum.matches("\\d{11}")) {
            return DesensitizedUtil.mobilePhone(mobileNum);
        }
        return mobileNum;
    }

    private PageData<GroupPurchaseListResponse> getGroupPurchaseListCommon(UserLoginCacheDTO sysUser, GroupPurchasePageDTO pageVO) {
        QGroupPurchaseRecordDO purchaseRecordDO = QGroupPurchaseRecordDO.groupPurchaseRecordDO;
        QActivityOrderRecordDO orderRecordDO = QActivityOrderRecordDO.activityOrderRecordDO;

        BooleanBuilder predicates = new BooleanBuilder();
        if (pageVO.getStatus() != null) {
            predicates.and(purchaseRecordDO.status.eq(pageVO.getStatus()));
        }
        predicates.and(orderRecordDO.isMaster.eq(1));
        predicates.and(orderRecordDO.status.eq(1));
        if (pageVO.getProductId() != null) {
            predicates.and(orderRecordDO.productId.eq(pageVO.getProductId()));
        }
        if (CollectionUtil.isNotEmpty(pageVO.getOrderIds())) {
            predicates.and(orderRecordDO.orderId.in(pageVO.getOrderIds()));
        }
        //拼团结束时间大于当前时间
        if (pageVO.getStartTime() != null) {
            predicates.and(purchaseRecordDO.endTime.gt(pageVO.getStartTime()));
        }
        //会员条件过滤
        if (pageVO.getMemberDTO() != null) {
            predicates.and(orderRecordDO.memberId.eq(pageVO.getMemberDTO().getMemberId()));
            predicates.and(orderRecordDO.roleId.eq(pageVO.getMemberDTO().getRoleId()));
        }
        JPAQuery<GroupPurchaseListDto> queryJpaQuery = queryFactory.select(Projections.bean(GroupPurchaseListDto.class,
                purchaseRecordDO.id,
                orderRecordDO.memberName,
                orderRecordDO.logo,
                orderRecordDO.memberId,
                orderRecordDO.roleId,
                orderRecordDO.orderId,
                purchaseRecordDO.endTime,
                purchaseRecordDO.assembleNum,
                purchaseRecordDO.num,
                purchaseRecordDO.validTime))
                .from(purchaseRecordDO)
                .innerJoin(orderRecordDO).on(orderRecordDO.objectId.eq(purchaseRecordDO.id));
        queryJpaQuery.where(predicates);
        long totalCount = queryJpaQuery.fetchCount();
        List<GroupPurchaseListDto> pageList = queryJpaQuery.orderBy(purchaseRecordDO.endTime.asc())
                .offset(pageVO.getCurrentOffset())
                .limit(pageVO.getPageSize())
                .fetch();

        List<GroupPurchaseListResponse> resultList = pageList.stream().map(o -> {
            GroupPurchaseListResponse resp = new GroupPurchaseListResponse();
            resp.setId(o.getId());
            resp.setLogo(o.getLogo());
            resp.setMemberName(mobileHide(o.getMemberName()));
            resp.setEndTime(o.getEndTime());
            resp.setNum(o.getAssembleNum() - o.getNum());
            if (sysUser != null) {
                resp.setInviteButton(o.getMemberId().equals(sysUser.getMemberId()) && o.getRoleId().equals(sysUser.getMemberRoleId()));
            }
            resp.setValidTime(o.getValidTime());
            resp.setOrderId(o.getOrderId());
            return resp;
        }).collect(Collectors.toList());
        return new PageData<>(totalCount, resultList);
    }

    @Override
    public Wrapper<PageData<GroupPurchaseListResponse>> getGroupPurchaseList(UserLoginCacheDTO sysUser, GroupPurchasePageRequest pageVO) {
        GroupPurchasePageDTO dto = new GroupPurchasePageDTO();
        dto.setCurrent(pageVO.getCurrent());
        dto.setPageSize(pageVO.getPageSize());
        dto.setProductId(pageVO.getProductId());
        dto.setStatus(GroupPurchaseStatusEnum.DOING.getCode());
        dto.setStartTime(System.currentTimeMillis());
        return Wrapper.success(getGroupPurchaseListCommon(sysUser, dto));
    }

    @Override
    public Wrapper<GroupPurchaseDetailResponse> getGroupPurchaseDetail(UserLoginCacheDTO sysUser, GroupPurchaseDetailRequest request) {
        GroupPurchaseRecordDO groupPurchaseRecordDO = groupPurchaseRecordRepository.findById(request.getId()).orElse(null);
        if (groupPurchaseRecordDO == null) {
            return Wrapper.success();
        }
        List<ActivityOrderRecordDO> orderList = activityOrderRecordRepository.findByObjectIdAndActivityType(request.getId(), ActivityTypeEnum.GROUP_PURCHASE.getCode());
        if (CollectionUtil.isEmpty(orderList)) {
            return Wrapper.success();
        }
        GroupPurchaseDetailResponse response = new GroupPurchaseDetailResponse();
        response.setStatus(groupPurchaseRecordDO.getStatus());
        response.setAssembleNum(groupPurchaseRecordDO.getAssembleNum());
        response.setNum(groupPurchaseRecordDO.getNum());
        response.setEndTime(groupPurchaseRecordDO.getEndTime());
        List<GroupPurchaseDetailItemResponse> itemList = orderList.stream().map(o -> {
            GroupPurchaseDetailItemResponse itemResponse = new GroupPurchaseDetailItemResponse();
            itemResponse.setLogo(o.getLogo());
            itemResponse.setIsMaster(o.getIsMaster());
            itemResponse.setMemberName(o.getMemberName());
            return itemResponse;
        }).collect(Collectors.toList());
        response.setItemList(itemList);
        //判断当前用户是否已参与拼团
        if (sysUser != null && orderList.stream().filter(o -> o.getMemberId().equals(sysUser.getMemberId()) && o.getRoleId().equals(sysUser.getMemberRoleId())).count() > 0) {
            response.setIsJoin(Boolean.TRUE);
        }
        return Wrapper.success(response);
    }

    @Override
    public Wrapper<GroupPurchaseDetailResponse> getOrderGroupPurchaseDetail(UserLoginCacheDTO sysUser, OrderGroupPurchaseDetailRequest request) {
        List<ActivityOrderRecordDO> orderRecordDOS = activityOrderRecordRepository.findByOrderId(request.getId());
        if (CollectionUtil.isEmpty(orderRecordDOS)) {
            throw new BusinessException(ResponseCode.SYSTEM_RECORDS_DON_T_EXIST);
        }
        ActivityOrderRecordDO orderRecord = orderRecordDOS.get(0);
        if (!orderRecord.getMemberId().equals(sysUser.getMemberId()) || !orderRecord.getRoleId().equals(sysUser.getMemberRoleId())) {
            throw new BusinessException(ResponseCode.DATA_AUTH_NOT_ALLOWED);
        }
        GroupPurchaseDetailRequest commonReq = new GroupPurchaseDetailRequest();
        commonReq.setId(orderRecord.getObjectId());
        return getGroupPurchaseDetail(sysUser, commonReq);
    }

    private PlatformActivityDO getPlatformActivityDOById(Long id) {
        return platformActivityRepository.findById(id).orElse(null);
    }

    private MerchantActivityDO getMerchantActivityDOById(Long id) {
        return merchantActivityRepository.findById(id).orElse(null);
    }

    private ActivityBaseInfoDto getActivityBaseInfo(Integer belongType, Long activityId) {
        ActivityBaseInfoDto dto = new ActivityBaseInfoDto();
        if (belongType == 1) {//平台
            PlatformActivityDO platformActivityDOById = getPlatformActivityDOById(activityId);
            GroupPurchaseBO groupPurchaseBO = (GroupPurchaseBO) platformActivityDOById.getActivityDefined();
            dto.setAssembleNum(groupPurchaseBO.getAssembleNum());
            dto.setValidTime(groupPurchaseBO.getAssembleTime());
        } else {
            MerchantActivityDO merchantActivityDOById = getMerchantActivityDOById(activityId);
            GroupPurchaseBO groupPurchaseBO = (GroupPurchaseBO) merchantActivityDOById.getActivityDefined();
            dto.setAssembleNum(groupPurchaseBO.getAssembleNum());
            dto.setValidTime(groupPurchaseBO.getAssembleTime());
        }
        return dto;
    }

    private GroupPurchaseRecordDO buildGroupPurchaseRecordDO(GroupPurchaseAddRequest req) {
        GroupPurchaseRecordDO recordDO = new GroupPurchaseRecordDO();
        Date now = new Date();
        recordDO.setCreateTime(now.getTime());
        recordDO.setStatus(GroupPurchaseStatusEnum.DOING.getCode());
        recordDO.setNum(1);
        ActivityBaseInfoDto activityBaseInfo = getActivityBaseInfo(req.getBelongType(), req.getActivityId());
        recordDO.setAssembleNum(activityBaseInfo.getAssembleNum());
        if (activityBaseInfo.getValidTime() == null || activityBaseInfo.getValidTime() == 0) {
            activityBaseInfo.setValidTime(24);
        }
        recordDO.setValidTime(activityBaseInfo.getValidTime());
        recordDO.setEndTime(DateUtil.offsetHour(now, activityBaseInfo.getValidTime()).getTime());
        return recordDO;
    }

    private ActivityOrderRecordDO buildActivityOrderRecordDO(GroupPurchaseAddRequest req) {
        ActivityOrderRecordDO recordDO = new ActivityOrderRecordDO();
        recordDO.setActivityId(req.getActivityId());
        recordDO.setBelongType(req.getBelongType());
        recordDO.setActivityType(ActivityTypeEnum.GROUP_PURCHASE.getCode());
        recordDO.setMemberId(req.getMemberId());
        recordDO.setRoleId(req.getRoleId());
        recordDO.setMemberName(req.getMemberName());
        recordDO.setLogo(req.getLogo());
        recordDO.setIsMaster(req.getId() == null ? 1 : 0);
        recordDO.setOrderId(req.getOrderId());
        recordDO.setProductId(req.getProductId());
        recordDO.setSkuId(req.getSkuId());
        recordDO.setStatus(1);
        recordDO.setQuantity(req.getQuantity());
        return recordDO;
    }

    /**
     * 保存拼团记录
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Long> addGroupPurchase(GroupPurchaseAddRequest req) {
        log.info("添加拼团，req:{}", JSONUtil.toJsonStr(req));
        //新增
        GroupPurchaseRecordDO recordDO;
        if (req.getId() == null) {
            recordDO = buildGroupPurchaseRecordDO(req);
            groupPurchaseRecordRepository.saveAndFlush(recordDO);
            ActivityOrderRecordDO activityOrderRecordDO = buildActivityOrderRecordDO(req);
            activityOrderRecordDO.setObjectId(recordDO.getId());
            activityOrderRecordRepository.save(activityOrderRecordDO);
            String key = MkRedisKeyConstants.getGroupPurchaseValidTimeKey(recordDO.getId());
            //默认时效24小时
            int validTime = recordDO.getValidTime() * 60 * 60;
            Boolean set = redisStringUtils.set(key, (recordDO.getAssembleNum() - 1) + "", (long) validTime, Constants.REDIS_MARKETING_INDEX);
            if (!set) {
                log.warn("创建拼团，保存缓存数据失败，Data: " + recordDO.getId());
                throw new BusinessException(ResponseCode.BUSINESS_ERROR);
            }
            //添加到mq 延时队列:单位是毫秒
            try {
                MarketingQueueDTO queueDTO=new MarketingQueueDTO(MkQueueMessageTypeEnum.GROUP_PURCHASE_TIMEOUT.getCode(),recordDO.getId() + "",validTime * 1000L);
                rabbitTemplate.convertAndSend(MkFeignConstants.MK_DELAY_EXCHANGE, MkFeignConstants.MK_DELAY_ROUTING_KEY, JSONUtil.toJsonStr(queueDTO), message -> {
                    message.getMessageProperties().setDelay(validTime * 1000);
                    return message;
                });
            } catch (Exception e) {
                log.error("拼团单添加到延时过期消息队列错误，Data: " + recordDO.getId() + ", Exception:", e);
                throw new BusinessException(ResponseCode.BUSINESS_ERROR);
            }
        } else {
            //参与拼团
            String key = MkRedisKeyConstants.getGroupPurchaseValidTimeKey(req.getId());
            Boolean exists = redisStringUtils.exists(key, Constants.REDIS_MARKETING_INDEX);
            if (!exists) {
                throw new BusinessException(ResponseCode.MARKETING_ACTIVITY_GOODS_GROUP_PURCHASE_OVER_ERROR);
            }
            //递减
            Long currentNum = redisStringUtils.decrement(key, 1, Constants.REDIS_MARKETING_INDEX);
            if (currentNum < 0) {
                //拼团超限
                //清空缓存
                redisStringUtils.del(key, Constants.REDIS_MARKETING_INDEX);
                //如果过期，更新拼团状态[被动触发超时的拼团]
                ((ActivityOrderServiceImpl) AopContext.currentProxy()).updateTimeOutGroupPurchase(req.getId());
                throw new BusinessException(ResponseCode.MARKETING_ACTIVITY_GOODS_GROUP_PURCHASE_OVERFLOW_ERROR);
            } else {
                //参与拼团
                //保存拼团记录
                recordDO = groupPurchaseRecordRepository.findById(req.getId()).orElse(null);
                if (recordDO == null) {
                    throw new BusinessException(ResponseCode.MARKETING_ACTIVITY_GOODS_GROUP_PURCHASE_NOT_EXISTS_ERROR);
                }
                int preAssembleNum = recordDO.getAssembleNum() - currentNum.intValue();
                if (recordDO.getNum() < preAssembleNum) {
                    recordDO.setNum(preAssembleNum);
                    groupPurchaseRecordRepository.saveAndFlush(recordDO);
                }
                ActivityOrderRecordDO activityOrderRecordDO = buildActivityOrderRecordDO(req);
                activityOrderRecordDO.setObjectId(recordDO.getId());
                activityOrderRecordRepository.saveAndFlush(activityOrderRecordDO);

                //最后一个拼团成功
                if (currentNum == 0) {
                    recordDO.setStatus(GroupPurchaseStatusEnum.SUCCESS.getCode());
                    groupPurchaseRecordRepository.saveAndFlush(recordDO);
                    //清空缓存
                    redisStringUtils.del(key, Constants.REDIS_MARKETING_INDEX);
                    // 事务提交后推送消息
                    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                        @Override
                        public void afterCommit() {
                            //通知订单服务
                            sendMsgListToOrderService(recordDO.getId(), 1);
                        }
                    });
                }
            }
        }
        return Wrapper.success(recordDO.getId());
    }

    /**
     * 更新超时拼团
     *
     * @param groupPurchaseId
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateTimeOutGroupPurchase(long groupPurchaseId) {
        log.info("1更新超时拼团 groupPurchaseId:{}", groupPurchaseId);
        GroupPurchaseRecordDO recordDO = groupPurchaseRecordRepository.findById(groupPurchaseId).orElse(null);
        if (recordDO == null) {
            log.warn("updateTimeOutGroupPurchase>拼团id{}不存在", groupPurchaseId);
            return;
        }
        if (!GroupPurchaseStatusEnum.DOING.getCode().equals(recordDO.getStatus())) {
            log.warn("updateTimeOutGroupPurchase>拼团已结束 拼团id{}", groupPurchaseId);
            return;
        }
        //拼团人数不够且已超时，设置拼团失败
        if (recordDO.getAssembleNum().compareTo(recordDO.getNum()) > 0 && recordDO.getEndTime().compareTo(System.currentTimeMillis()) < 0) {
            log.info("2更新超时拼团 groupPurchaseId:{}", groupPurchaseId);
            recordDO.setStatus(GroupPurchaseStatusEnum.FAIL.getCode());
            groupPurchaseRecordRepository.saveAndFlush(recordDO);
            //发送消息到订单服务
            sendMsgListToOrderService(groupPurchaseId, 0);
        }
    }

    /**
     * 接收拼团mq拼团到期通知
     *
     * @param groupPurchaseId
     */
    @Transactional
    @Override
    public void updateGroupPurchaseStatus(long groupPurchaseId) {
        log.info("收到拼团延时队列消息 groupPurchaseId:{}", groupPurchaseId);
        GroupPurchaseRecordDO recordDO = groupPurchaseRecordRepository.findById(groupPurchaseId).orElse(null);
        if (recordDO == null) {
            log.warn("updateGroupPurchaseStatus>拼团id{}不存在", groupPurchaseId);
            return;
        }
        if (!GroupPurchaseStatusEnum.DOING.getCode().equals(recordDO.getStatus())) {
            log.warn("updateGroupPurchaseStatus>拼团已结束 拼团id{}", groupPurchaseId);
            return;
        }
        int status = 1;
        //step1:更新拼团状态为失败
        if (recordDO.getAssembleNum().compareTo(recordDO.getNum()) <= 0) {
            recordDO.setStatus(GroupPurchaseStatusEnum.SUCCESS.getCode());
        } else {
            recordDO.setStatus(GroupPurchaseStatusEnum.FAIL.getCode());
            status = 0;
        }
        groupPurchaseRecordRepository.saveAndFlush(recordDO);
        //发送消息到订单服务
        sendMsgListToOrderService(groupPurchaseId, status);

    }

    /**
     * @param groupPurchaseId
     * @param status          拼团状态，0-拼团失败，1-拼团成功
     */
    private void sendMsgListToOrderService(Long groupPurchaseId, Integer status) {
        //发送消息给订单服务
        List<ActivityOrderRecordDO> activityOrderList = activityOrderRecordRepository.findByObjectIdAndActivityType(groupPurchaseId, ActivityTypeEnum.GROUP_PURCHASE.getCode());
        List<OrderGroupDTO> dtoList = new ArrayList<>();
        for (ActivityOrderRecordDO activityOrderRecordDO : activityOrderList) {
            OrderGroupDTO dto = new OrderGroupDTO();
            dto.setOrderId(activityOrderRecordDO.getOrderId());
            dto.setStatus(status);
            dto.setGroupPurchaseId(activityOrderRecordDO.getObjectId());
            dtoList.add(dto);
        }
        log.info("收到拼团延时队列消息,发送给订单mq groupPurchaseId:{}, dtoList:{}", groupPurchaseId, JSONUtil.toJsonStr(dtoList));
        //通知订单服务
        for (OrderGroupDTO dto : dtoList) {
            sendMsgToOrderService(dto);
        }
        log.info("收到拼团延时队列消息,发送给订单mq groupPurchaseId:{} 完成",groupPurchaseId);
    }

    private void sendMsgToOrderService(OrderGroupDTO dto) {
        //通知订单服务
        rabbitMQUtils.sendMsg(OrderFeignConstant.ORDER_GROUP_EXCHANGE, OrderFeignConstant.ORDER_GROUP_ROUTINGKEY, JSONUtil.toJsonStr(dto));
        log.info("收到拼团延时队列消息,发送给订单mq dto:{}", JSONUtil.toJsonStr(dto));
    }

    @Override
    public Wrapper<List<OrderListGroupPurchaseResponse>> getOrderListGroupPurchase(UserLoginCacheDTO sysUser, OrderListGroupPurchaseRequest request) {
        GroupPurchasePageDTO dto = new GroupPurchasePageDTO();
        dto.setOrderIds(request.getIds());
        dto.setMemberDTO(new MemberAndRoleIdDTO(sysUser.getMemberId(), sysUser.getMemberRoleId()));
        PageData<GroupPurchaseListResponse> groupPurchaseListCommon = getGroupPurchaseListCommon(sysUser, dto);
        List<OrderListGroupPurchaseResponse> responseList = null;
        if (CollectionUtil.isNotEmpty(groupPurchaseListCommon.getData())) {
            responseList = groupPurchaseListCommon.getData().stream().map(o -> {
                OrderListGroupPurchaseResponse response = new OrderListGroupPurchaseResponse();
                response.setEndTime(o.getEndTime());
                response.setValidTime(o.getValidTime());
                response.setNum(o.getNum());
                response.setOrderId(o.getOrderId());
                response.setId(o.getId());
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(responseList);
    }

    @Override
    public Wrapper<Boolean> isRepeatJoinGroupPurchase(GroupPurchaseCheckRequest req) {
        List<ActivityOrderRecordDO> groupPurchaseList = activityOrderRecordRepository.findByObjectIdAndActivityTypeAndMemberIdAndRoleId(req.getId(), ActivityTypeEnum.GROUP_PURCHASE.getCode(), req.getMemberId(), req.getRoleId());
        return Wrapper.success(groupPurchaseList.size()>0);
    }

    @Override
    public Wrapper<GroupPurchaseShareDetailResponse> getOrderGroupPurchaseShareDetail(UserLoginCacheDTO sysUser, OrderGroupPurchaseDetailRequest request) {
        List<ActivityOrderRecordDO> orderRecordDOS = activityOrderRecordRepository.findByOrderId(request.getId());
        if (CollectionUtil.isEmpty(orderRecordDOS)) {
            throw new BusinessException(ResponseCode.SYSTEM_RECORDS_DON_T_EXIST);
        }
        ActivityOrderRecordDO orderRecord = orderRecordDOS.get(0);
        if (!orderRecord.getMemberId().equals(sysUser.getMemberId()) || !orderRecord.getRoleId().equals(sysUser.getMemberRoleId())) {
            throw new BusinessException(ResponseCode.DATA_AUTH_NOT_ALLOWED);
        }
        //拼团信息
        GroupPurchaseRecordDO groupPurchaseRecordDO = groupPurchaseRecordRepository.findById(orderRecord.getObjectId()).orElse(null);
        GroupPurchaseShareDetailResponse commonReq = new GroupPurchaseShareDetailResponse();
        commonReq.setAssembleNum(groupPurchaseRecordDO.getAssembleNum());
        //商城信息
        List<ActivityShopDO> shopDOList = shopRepository.findByBelongTypeAndActivityId(orderRecord.getBelongType(), orderRecord.getActivityId());
        if(CollectionUtil.isNotEmpty(shopDOList)){
            Set<Integer> envSet = shopDOList.stream().map(o -> o.getEnvironment()).collect(Collectors.toSet());
            commonReq.setEnvironmentList(new ArrayList<>(envSet));
        }
        //商品信息
        ActivityGoodsDO activityGoodsDO = goodsRepository.findAllByBelongTypeAndActivityIdAndSkuId(orderRecord.getBelongType(), orderRecord.getActivityId(), orderRecord.getSkuId());
        commonReq.setProductName(activityGoodsDO.getProductName());
        commonReq.setProductId(activityGoodsDO.getProductId());
        commonReq.setSkuId(activityGoodsDO.getSkuId());
        commonReq.setPrice(activityGoodsDO.getPrice());
        commonReq.setActivityPrice(activityGoodsDO.getActivityPrice());
        commonReq.setSupplierMemberId(activityGoodsDO.getMemberId());
        commonReq.setSupplierRoleId(activityGoodsDO.getRoleId());
        commonReq.setProductImgUrl(activityGoodsDO.getProductImgUrl());
        //活动结束时间
        ActivityCommonInfoDTO activityInfo= baseActivityService.getActivityInfoNoCache(orderRecord.getBelongType(), orderRecord.getActivityId());
        Boolean online=(activityInfo.getOnline()&&activityInfo.getEndTime().compareTo(System.currentTimeMillis())>0);
        commonReq.setOnline(online);
        return Wrapper.success(commonReq);
    }
}
